package com.borened.common.core.serializer;

import cn.hutool.core.util.ObjectUtil;
import com.borened.common.core.annotation.BigDecimalFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author jianghh
 */
@NoArgsConstructor
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> implements ContextualSerializer {

    private int scale;

    @Override
    public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
            throws IOException {
        if (!ObjectUtil.isEmpty(bigDecimal)) {
            jsonGenerator.writeNumber(bigDecimal.setScale(scale, RoundingMode.HALF_UP));
        } else {
            jsonGenerator.writeNumber(0.00);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty)
            throws JsonMappingException {
        BigDecimalFormat annotation = beanProperty.getAnnotation(BigDecimalFormat.class);
        if (!ObjectUtil.isEmpty(annotation)) {
            this.scale = annotation.scale();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}
